const app = getApp();
const SocketTask = app.globalData.SocketTask;
Page({
  data: {
    userInfo: {
      avatarUrl: '',
      nickName: '张三',
      identity: "",
    },
    messageNum: 10,
    cardInfo: {
      his: "", // 已借阅
      log: "", //  待还
    },
    cardNum: "99+",
    isBind: true,
    isAuth: 0,
    flag: true, // 测试是否是第一次进来是否授权了
    isBindWx: false
  },
  // 
  // 退出登录
  exitLogin() {
    this
      .axios
      .remove('Session')
      .then(() => {
        // 先取出来保存
        let username = wx.getStorageSync('cacheName')
        this.Store.clear();
        // 再写入
        wx.setStorageSync('cacheName',username);
        this.Router.push({
          path: "login",
          openType: 'reLaunch',
        })
      })
  },
  // 消息中心
  toMessage() {
    this.Router.push('message');
  },
  // 修改密码
  toPassWord() {
    this.Router.push('passWord');
  },
  // 从存储空间获取用户信息
  setUser() {
    let { userInfo } = this.data
    userInfo.nickName = this.Store.getItem('personName');
    userInfo.avatarUrl = this.Store.getItem('headUrl');
    userInfo.identity = this.Store.getItem("identity");
    let isbind = this.Store.getItem("bindWeChat");
    isbind = Boolean(isbind);
    this.setData({
      userInfo,
      isBindWx: isbind
    })
  },
  // 权限判定
  powerJuge(arr) {
    let powerItem = wx.getStorageSync('power');
    //powerItem = ',' + powerItem + ',';
    let temp = arr.filter((item) => {
      let power = item.power;
      //let power = ',' + item.power + ',';
      if (powerItem.indexOf(power) > -1) {
        return item
      }
      if (power == 'allHave') {
        return item
      }
    })
    console.log(temp)
    return temp
  },
  // 钩子函数
  onLoad() {

    this.setUser();
    this._getMessage();
  },
  // 每次展现出来
  onShow() {
    const that = this;
    // tabbar
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      console.log(this.getTabBar(), '坚持练习不知道')
      // 第一次初始化
      let list = this.getTabBar().data.list;
      let tempArr = this.powerJuge(list);
      // 匹配索引 因为索引根据权限会动态变化
      //let tempArr = this.getTabBar().data.itemMenu
      let index = tempArr.findIndex((item) => {
        if (item.power == 'allHave') {
          return true
        }
      })
      console.log(index, '索引')
      this.getTabBar().setData({
        itemMenu: tempArr,
        selected: index
      })
    }

    this._getMessage();


    // SocketTask.onOpen((open) => {
    //   console.log("Websocket open");
    // })

    // SocketTask.onClose((close) => {
    //   console.log("webSocket close");
    // })

    // SocketTask.onError((err) => {
    //   console.log(err);
    //   wx.showToast({ title: err });
    // })

    // SocketTask.onMessage((val) => {
    //   // 这里接收信息 如果匹配上就更新消息数据

    //   console.log(val);
    // })
    // SocketTask.send({
    //   data: '发送测试',

    // })

  },

  /* Api */
  // 获取消息数量
  bindWx() {
    let self = this;
    wx.showModal({
      content: '是否进行微信绑定',
      success(res) {
        if (res.confirm) {
          wx.login({
            success(res) {
              if (res.code) {
                //发起网络请求
                self.axios.noToken('WeChat/getAppletUnionId', { code: res.code }, "POST").then((res) => {
                  if (res.code == '200') {
                    let obj = {};
                    obj.openId = res.data.openid
                    obj.userId = wx.getStorageSync('userid');
                    self.axios.add('WeChatUser', obj).then((res) => {
                      // 把本地的显示绑定值修改
                      if (res.code == '200') {
                        self.Store.setItem('"bindWeChat', true)
                        self.setData({
                          isBindWx: true
                        })
                        wx.showToast({
                          title: '绑定成功',
                          icon: 'success',
                          duration: 2000
                        })
                      }
                      console.log(res,'绑定卡号')
                    })
                  }
                  console.log(res,'无token')
                })
              } else {
                wx.showToast({
                  title: '登录失败！',
                  icon: 'success',
                  duration: 2000
                })
                console.log('登录失败！' + res.errMsg)
              }
            }
          })

        } else if (res.cancel) {

        }
      }
    })
  },
  ubBindWx() {
    let self = this
    let userId = wx.getStorageSync('userid');
    wx.showModal({
      content: '是否解除绑定',
      success(res) {
        if (res.confirm) {
          self.axios.remove('WeChatUser', userId).then((res) => {
            if (res.code == '200') {
              // 更改本地的绑定参数
              self.Store.setItem('"bindWeChat', false)
              self.setData({
                isBindWx: false
              })
              wx.showToast({
                title: '解绑成功',
                icon: 'success',
                duration: 2000
              })
            } else {

            }

          })

        } else if (res.cancel) {

        }
      }
    })
  },
  _getMessage() {
    let userId = this.Store.getItem('userid')
    this.axios
      .custom("Message", "getMessages", userId)
      .then((res) => {
        if (res.code == 200) {
          let count = Number(res.data);
          if (count > 99) {
            count = '99+';
          }
          this.setData({
            messageNum: count
          })
        } else {
          console.log(res, '数据格式变动')
        }
      })
      .catch((e) => {
        console.log("错误信息", e);
      });
  },
  toExample() {
    wx.navigateTo({
      url: "/packageA/chart/index"
    })
  },
  /**
   * 暂时废弃的功能 有可能还会被使用
   */
  // 更多资料
  toMyInfo() {
    wx.navigateTo({
      url: "../userMode/myInfo/myInfo",
      events: {

      },
      success() {
        console.log('调换成功')
      }
    })
  },
  // 路由跳转
  toCollect() {
    wx.navigateTo({
      url: "/pages/userMode/collect/collect",
      events: {

      },
      success() {
        console.log('调换成功')
      }
    })
  },
  toBorRet() {
    wx.navigateTo({
      url: "../../component/tab/index",
      events: {

      },
      success() {
        console.log('调换成功')
      }
    })
  },
  toReaderCard() {

    wx.navigateTo({
      url: "../userMode/readerCard/readerCard",
      events: {

      },
      success() {
        console.log('调换成功')
      }
    })
  },
  toUnbind() {
    wx.navigateTo({
      url: "../userMode/unBindCard/unBindCard",
    })
  },
  toBill() {
    wx.navigateTo({
      url: "../userMode/bill/bill",
    })
  },
  toAboutUs() {
    wx.navigateTo({
      url: "../userMode/about/about",
    })
  },
  toSuggestion() {
    wx.navigateTo({
      url: "../userMode/suggestion/suggestion",
    })
  },
  init() {
    // 判定是否授权 授权后渲染头像和名字
    let isAuth = wx.getStorageSync('isAuth') || 0;
    console.log(isAuth, '到底授权没')
    let token = wx.getStorageSync('token') || ''
    this.setData({
      isAuth: isAuth
    })
    // 判定是否授权
    if (isAuth) {
      let {
        avatarUrl,
        nickName
      } = App.globalData.userInfo
      console.log(avatarUrl, nickName)
      this.setData({
        userInfo: App.globalData.userInfo
      })
    }
    // 判定是否绑卡
    if (token) {
      Store.setItem('entry', true); // 第一次进来是否授权
      this.setData({
        isBind: true,

      })
      this._getUserInfo()
      this._getNumbers()
    } else {
      Store.setItem('entry', false);
    }
    // 判定是否绑定卡号 授权后 调取用户信息
    console.log(App, '开始获取用户信息')
  },
  toBindCard() {
    wx.navigateTo({
      url: "../bindCard/bindCard",
    })
  },
  // API
  _getNumbers(params = {}) {
    let url = Ip + Api.index.numbers
    let data = params
    axios(url, data, 'GET').then((res) => {
      if (res.state) {
        let data = res.row
        this.setData({
          cardInfo: data
        })
      }
      console.log(res, '借阅数量')
    })
  },
  // 登录授权
  _login(params = {}) {
    // let url = Ip + Api.index.login
    // let data = params
    // axios(url, data, 'POST').then((res) => {
    //   if (res.state) {
    //     App.globalData.card.openId = res.row.openId
    //     App.globalData.card.sessionKey = res.row.sessionKey
    //     App.globalData.card.skey = res.row.skey
    //     wx.setStorageSync('token', res.row.authorization)
    //     // 判定是否绑了卡 绑卡开始刷新页面
    //     let token = res.row.authorization
    //     if (token) {
    //       this.setData({
    //         isBind: true,
    //       })
    //       this._getUserInfo()
    //       this._getNumbers()
    //     } else {
    //       this.setData({
    //         isBind: false,
    //       })
    //     }
    //   }




    //   console.log('授权换token', res)
    // })
  },
  _getUserInfo(params = {}) {
    let url = Ip + Api.index.getUser
    let data = params
    axios(url, data, 'GET').then((res) => {
      if (res.state) {

        let number = res.row.cardNumber
        this.setData({
          cardNum: number
        })
      }


      console.log(res, '用户信息')
    })
  },
  onGotUserInfo(e) {
    console.log(e, '权限')
    // if (e.detail.signature) {
    //   this.setData({
    //     isAuth: 1
    //   })
    //   // 开始存储信息 并且发送登录请求获取token
    //   App.globalData.userInfo = e.detail.userInfo
    //   App.globalData.user = e.detail
    //   let obj = {}
    //   obj.code = App.globalData.code
    //   obj = Object.assign(obj, e.detail)
    //   wx.setStorageSync('isAuth', 1)
    //   let {
    //     avatarUrl,
    //     nickName
    //   } = App.globalData.userInfo
    //   console.log(avatarUrl, nickName)
    //   this.setData({
    //     userInfo: App.globalData.userInfo
    //   })
    //   this._login(obj)
    // } else {
    //   console.log('没授权吧')
    // }
  },



})